﻿using System;
using System.Linq;
using System.Linq.Expressions;
using System.Collections.Generic;
using System.Runtime.Serialization;

namespace QbservableCore.Serialization
{
    [DataContract]
    public class InvocationNode : ExpRepresentationBase
    {
        [DataMember]
        public ExpRepresentationBase TargetExpression { get; set; }

        [DataMember]
        public ExpRepresentationBase[] Arguments { get; set; }

        protected internal override Expression ToExpression(ExepressionBuilderCache exepressionBuilderCache)
        {
            return Expression.Invoke(TargetExpression.ToExpression(exepressionBuilderCache), Arguments.Select(arg => arg.ToExpression(exepressionBuilderCache)).ToArray());
        }

        protected override void TraverseChildren(Func<ExpRepresentationBase, ExpRepresentationBase> action)
        {
            TargetExpression = TargetExpression.Traverse(action);
            TraverseNodes(Arguments, action);
        }

        public override string ToString()
        {
            string args = string.Join(", ", Arguments.Cast<object>());
            return string.Format("Invoke:{0}({1})", TargetExpression, args);
        }
    }
}